package com.sj.hh.mvp.presenter.impl;

import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;

import com.sj.friendcircle.lib.mvp.IBasePresenter;
import com.sj.friendcircle.lib.utils.ToolUtil;
import com.sj.friendcircle.ui.widget.commentwidget.CommentWidget;
import com.sj.hh.mvp.callback.OnCommentChangeCallback;
import com.sj.hh.mvp.callback.OnDeleteCallback;
import com.sj.hh.mvp.callback.OnLikeChangeCallback;
import com.sj.hh.mvp.presenter.IMomentPresenter;
import com.sj.hh.mvp.view.IMomentView;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.rongcloud.im.server.response.friendcircle.CommentInfo;
import cn.rongcloud.im.server.response.friendcircle.LikesInfo;
import cn.rongcloud.im.server.response.friendcircle.MomentsInfo;
import cn.rongcloud.im.server.response.user.UserInfo;
import cn.rongcloud.im.user.UserManager;


/**
 * Created by huluhong on 2018/7/7.
 * <p>
 * 朋友圈presenter
 */

public class MomentPresenter implements IMomentPresenter {
    private IMomentView momentView;
    private DeleteDynamicImpl deleteDynamic;
    private CommentImpl commentModel;
    private LikeImpl likeModel;

    public MomentPresenter() {
        this(null);
    }

    public MomentPresenter(IMomentView momentView) {
        this.momentView = momentView;
        commentModel = new CommentImpl();
        likeModel = new LikeImpl();
        deleteDynamic = new DeleteDynamicImpl();
    }

    @Override
    public IBasePresenter<IMomentView> bindView(IMomentView view) {
        this.momentView = view;
        return this;
    }

    @Override
    public IBasePresenter<IMomentView> unbindView() {
        return this;
    }

    //=============================================================动作控制
    @Override
    public void addLike(final Context context, final int viewHolderPos, final String momentid, final List<LikesInfo> currentLikeList, final MomentsInfo.DataBean dataBean) {
        likeModel.addLike(context,momentid, new OnLikeChangeCallback() {
            @Override
            public void onLike(String likeinfoid) {
                List<LikesInfo> resultLikeList = new ArrayList<LikesInfo>();
                if (!ToolUtil.isListEmpty(currentLikeList)) {
                    resultLikeList.addAll(currentLikeList);
                }

                UserInfo userInfo = UserManager.getInstance().getUserInfo(context);
                boolean hasLocalLiked = findLikeInfoPosByUserid(resultLikeList, userInfo.getUserid()) > -1;
                if (!hasLocalLiked && !TextUtils.isEmpty(likeinfoid)) {
                    LikesInfo info = new LikesInfo();
                    info.setMomentsid(dataBean);
                    info.setUserInfo(userInfo);
                    resultLikeList.add(info);
                }
                if (momentView != null) {
                    momentView.onLikeChange(viewHolderPos, resultLikeList);
                }
            }

            @Override
            public void onUnLike() {

            }

        });
    }

    @Override
    public void unLike(final Context context, final int viewHolderPos, String likesid, final List<LikesInfo> currentLikeList, MomentsInfo.DataBean info) {
        likeModel.unLike(context,likesid, new OnLikeChangeCallback() {
            @Override
            public void onLike(String likeinfoid) {

            }

            @Override
            public void onUnLike() {
                List<LikesInfo> resultLikeList = new ArrayList<LikesInfo>();
                if (!ToolUtil.isListEmpty(currentLikeList)) {
                    resultLikeList.addAll(currentLikeList);
                }

                UserInfo userInfo = UserManager.getInstance().getUserInfo(context);
                final int localLikePos = findLikeInfoPosByUserid(resultLikeList, userInfo.getUserid());
                if (localLikePos > -1) {
                    resultLikeList.remove(localLikePos);
                }
                if (momentView != null) {
                    momentView.onLikeChange(viewHolderPos, resultLikeList);
                }
            }

        });
    }

    /**
     * 添加评论
     *
     * @param context
     * @param viewHolderPos
     * @param momentid
     * @param replyUserid
     * @param commentContent
     * @param currentCommentList
     */
    @Override
    public void addComment(Context context, final int viewHolderPos, String momentid, String replyUserid, String commentContent, final List<CommentInfo> currentCommentList) {
        if (TextUtils.isEmpty(commentContent)) return;
        UserInfo userInfo = UserManager.getInstance().getUserInfo(context);
        commentModel.addComment(context, momentid, userInfo.getUserid(), userInfo, replyUserid, null, commentContent, new OnCommentChangeCallback() {
            @Override
            public void onAddComment(CommentInfo response) {
                List<CommentInfo> commentList = new ArrayList<CommentInfo>();
                if (!ToolUtil.isListEmpty(currentCommentList)) {
                    commentList.addAll(currentCommentList);
                }
                commentList.add(response);
                KLog.i("comment", "评论成功 >>>  " + response.toString());
                if (momentView != null) {
                    momentView.onCommentChange(viewHolderPos, commentList);
                }

            }

            @Override
            public void onDeleteComment(String response) {

            }
        });
    }

    @Override
    public void deleteComment(Context context, final int viewHolderPos, String commentid, final List<CommentInfo> currentCommentList) {
        if (TextUtils.isEmpty(commentid)) return;
        commentModel.deleteComment(context,commentid, new OnCommentChangeCallback() {
            @Override
            public void onAddComment(CommentInfo response) {

            }

            @Override
            public void onDeleteComment(String commentid) {
                if (TextUtils.isEmpty(commentid)) return;
                List<CommentInfo> resultLikeList = new ArrayList<CommentInfo>();
                if (!ToolUtil.isListEmpty(currentCommentList)) {
                    resultLikeList.addAll(currentCommentList);
                }
                Iterator<CommentInfo> iterator = resultLikeList.iterator();
                while (iterator.hasNext()) {
                    CommentInfo info = iterator.next();
                    if (TextUtils.equals(info.getCommentid()+"", commentid)) {
                        iterator.remove();
                        break;
                    }
                }
                KLog.i("comment", "删除评论成功 >>>  " + commentid);
                if (momentView != null) {
                    momentView.onCommentChange(viewHolderPos, resultLikeList);
                }

            }
        });

    }

    @Override
    public void deleteMoments(final Context context, @NonNull final MomentsInfo.DataBean momentsInfo) {
        assert momentsInfo != null : "momentsInfo为空";
        new AlertDialog.Builder(context)
                .setTitle("删除动态")
                .setMessage("确定删除吗？")
                .setNegativeButton("取消", null)
                .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteDynamic.deleteDynamic(context, momentsInfo.getTrendsId() + "", new OnDeleteCallback() {
                            @Override
                            public void onDeleteSuccess(String likeinfoid) {
                                try {
                                    if (momentsInfo.getTrendsImg() != null) {
                                        StringBuilder imgs = new StringBuilder();
                                        int id = 0;
                                        for (MomentsInfo.DataBean.TrendsImgBean imgBean : momentsInfo.getTrendsImg()) {
                                            imgs.append(imgBean.getId());
                                            if (id + 1 < momentsInfo.getTrendsImg().size())
                                                imgs.append(",");
                                            id++;
                                        }
                                        deleteFiles(context, imgs.toString());
                                        momentView.onDeleteMomentsInfo(momentsInfo);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onDeleteImageSuccess() {

                            }
                        });
                    }
                }).show();
    }

    private void deleteFiles(Context context, String ids) {
        deleteDynamic.deleteDynamicImage(context, ids, new OnDeleteCallback() {
            @Override
            public void onDeleteSuccess(String likeinfoid) {

            }

            @Override
            public void onDeleteImageSuccess() {

            }
        });
//        if (momentsInfo == null) return;
//        final List<String> pics = momentsInfo.getContent().getPics();
//        if (ToolUtil.isListEmpty(pics)) return;
//        for (final String pic : pics) {
//            BmobFile file = new BmobFile();
//            file.setUrl(pic);
//            file.delete(new UpdateListener() {
//                @Override
//                public void done(BmobException e) {
//                    if (e == null) {
//                        KLog.d("delPic", "文件删除成功 : " + pic);
//                    } else {
//                        KLog.d("delPic", "文件删除失败：" + e.getErrorCode() + "," + e.getMessage());
//                    }
//                }
//            });
//        }
    }


    public void showCommentBox(@Nullable View viewHolderRootView, int itemPos, String momentid, @Nullable CommentWidget commentWidget) {
        if (momentView != null) {
            momentView.showCommentBox(viewHolderRootView, itemPos, momentid, commentWidget);
        }
    }


    private int findLikeInfoPosByUserid(List<LikesInfo> infoList, String id) {

        int result = -1;
        if (ToolUtil.isListEmpty(infoList)) return result;
        for (int i = 0; i < infoList.size(); i++) {
            LikesInfo info = infoList.get(i);
            if (TextUtils.equals(info.getUserInfo().getUserid(), id)) {
                result = i;
                break;
            }
        }
        return result;
    }


    //------------------------------------------interface impl-----------------------------------------------
}
